package noema.serviceTask;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;

import org.apache.log4j.Logger;
import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;

@Stateless
public class ServiceTaskHandler implements WorkItemHandler {

	@Resource(mappedName = "java:/XAConnectionFactory")
	private ConnectionFactory connFactory;
	@Resource(mappedName = "topic/analysisService")
	private Topic dest;
	private Logger log=Logger.getLogger(ServiceTaskHandler.class);
	
	@Override
	public void abortWorkItem(WorkItem i, WorkItemManager m) {
		m.abortWorkItem(i.getId());
	}

	@SuppressWarnings("unchecked")
	@Override
	public void executeWorkItem(WorkItem i, WorkItemManager m) {
		log.info("Execute Service task param="+i.getParameters());
		Map<String, Object> params=i.getParameters();
		List<String> analysis=null;
		for(String key:params.keySet()){
			if(params.get(key) instanceof List<?>){
				List<?> list=(List<?>)params.get(key);
				if(!list.isEmpty()){
					if(list.get(0) instanceof String){
						analysis=(List<String>)list;
					}else if(analysis==null){
						analysis=(List<String>)list;
					}
				}
			}
		}
		if(analysis==null){
			throw new IllegalArgumentException("Service Task need at least one List<String> parameter");
		}
		
		
		try {
			Connection jmsConn = connFactory.createConnection();
			Session jmsSession = jmsConn.createSession(true,
					Session.AUTO_ACKNOWLEDGE);
			MessageProducer jmsProducer = jmsSession.createProducer(dest);
			MapMessage jmsMess = jmsSession.createMapMessage();
			for(String s:analysis){
				jmsMess.setString(s, s);
			}
			jmsMess.setLong("processInstanceId", i.getProcessInstanceId());
			jmsProducer.send(jmsMess);
			jmsSession.commit();
			jmsSession.close();
			jmsConn.close();
			log.info("Send jmsMessage: "+jmsMess);
		} catch (JMSException e) {
			e.printStackTrace();
			m.abortWorkItem(i.getId());
		}
		m.completeWorkItem(i.getId(), new HashMap<String, Object>());
	}

}
